// ClientSocket.cpp : implementation file
//

#include "stdafx.h"
#include "IEC104_Tool.h"
#include "ClientSocket.h"
#include "IEC104_ToolView.h"
#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CClientSocket

CClientSocket::CClientSocket()
{
	isCreated=false;
	isConected=false;

	m_Kill = TRUE ;
	m_nTimeOut = 1 ;
	
	struct linger Ling;
	Ling.l_onoff	= 1;
	Ling.l_linger	= 2;
	
	SetSockOpt( SO_LINGER, &Ling, sizeof(Ling) );   
}

CClientSocket::~CClientSocket()
{
	isCreated=false;
	isConected=false;
}


// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CClientSocket, CSocket)
//{{AFX_MSG_MAP(CClientSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif	// 0

/////////////////////////////////////////////////////////////////////////////
// CClientSocket member functions

void CClientSocket::OnClose(int nErrorCode) 
{
	// TODO: Add your specialized code here and/or call the base class
	m_pParentWnd->SendMessage(WM_CLOSEMSG,(WPARAM)this,(LPARAM)0);
	m_Kill = TRUE;  
	CSocket::OnClose(nErrorCode);
}

void CClientSocket::OnReceive(int nErrorCode) 
{
	int nLen = Receive(recv_buffer,RX_BUFF);
	if( nLen>0 )
	{
		CMainFrame *pMainFrm = (CMainFrame *)m_pParentWnd;
		InQueue((BYTE *)recv_buffer, &pMainFrm->NetRecvQueue, nLen);
		m_pParentWnd->SendMessage( WM_UPDATEMSG, (WPARAM)recv_buffer, (LPARAM)nLen );
	}
	CSocket::OnReceive(nErrorCode);
}


BOOL CClientSocket::ConnectHelper(const SOCKADDR* lpSockAddr, int nSockAddrLen)   
{   
	if (m_pbBlocking != NULL)   
	{   
		WSASetLastError(WSAEINPROGRESS);   
		return     FALSE;   
	}   
	
	m_nConnectError = -1;   
	
	if (!CAsyncSocket::ConnectHelper(lpSockAddr, nSockAddrLen))   
	{   
		if (GetLastError() == WSAEWOULDBLOCK)   
		{   
			//   Insert....   
			CTime curt, st;   
			CTimeSpan span(0, 0, 0, m_nTimeOut);   
			
			st = CTime().GetCurrentTime();   
			//.......   
			while(PumpMessages(FD_CONNECT))   
			{   
				if( m_nConnectError != -1 )   
				{   
					WSASetLastError(m_nConnectError);   
					return (m_nConnectError == 0);   
				}
				//   Insert....   
				curt = CTime().GetCurrentTime();   
				if( curt > (st+span) )   
					return   FALSE;   
				//..............   
			}
		}
		return   FALSE;   
	}
	m_Kill = FALSE;
	return TRUE;   
}   


